//
//  RHMeAssetContainVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/6.
//

#import "RHMeAssetContainVC.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import "RHAddPlantViewController.h"
#import "RHAddMePlantVC.h"
#import "RHMePlantListVC.h"
#import "RHPlantListViewCell.h"
#import "RHPlantModel.h"
#import "RHPlantInfoViewController.h"
#import "IFMMenu.h"
#import "KWTPlantGroupListVC.h"
#import "KWTAddPlantGroupVC.h"
#import "RHGolobalSetModel.h"
#import "RHVppGroupSetView.h"
#import "RHAssetSystemListVC.h"
#import "RHDeviceListFilterVC.h"
#import "RHAddAssetSystemVC.h"
#import "RHAddDeviceController.h"
#import "RHDeviceFilterView.h"
#import "RHUserModel.h"
#import "RHEndpointVC.h"
#import "KWTPlantGroupListVC.h"
#import "KWTAddPlantGroupVC.h"
#import "RHBatchPlantGroupConfigVC.h"

@interface RHMeAssetContainVC ()<JXCategoryListContainerViewDelegate,JXCategoryViewDelegate,JXCategoryTitleViewDataSource,QMUITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *titles;

@property (nonatomic, strong) JXCategoryTitleView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;

@property (nonatomic, strong) RHGolobalSetModel *vppConfigModel;


@end

@implementation RHMeAssetContainVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"资产".rh_localized];
    [self.view setBackgroundColor:CFTabViewBgColor];
    /* 管理层  --> 显示电站,资产,设备
     1.如果是 品牌用户和品牌用户的一级用户,只显示设备,因为一级用户下分了 户储和工商储
     2.如果是 一级用户以下的管理层 (户储类型: 显示 电站和设备) (工商储类型:显示 电站,系统,设备)
     用户层
     1.只显示电站和设备
     */
    self.titles = @[@"分组".rh_localized,
                    @"电站".rh_localized,
                    @"设备".rh_localized,
                    @"部件".rh_localized].mutableCopy;
    //工商储类型
    if ([PrivateMange share].currentUser.operationType == OperationTypeIndustry) {
        
        self.titles = @[@"分组".rh_localized,
                        @"电站".rh_localized,
                        @"系统".rh_localized,
                        @"设备".rh_localized,
                        @"部件".rh_localized].mutableCopy;
        
    }
    
    
    [self setupUI];
}


- (void)setupUI{
    
    kWeakSelf;
    //只有终端用户才能添加电站
    //    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
    
    QMUIButton *addButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
    [addButton setImage:[UIImage imageNamed:@"kwt_add_plant"] forState:UIControlStateNormal];
    [addButton setBackgroundColor:UIColor.clearColor];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    QMUIButton *configButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
    [configButton setImage:[UIImage imageNamed:@"plant_chg_config2"] forState:UIControlStateNormal];
    [configButton setBackgroundColor:UIColor.clearColor];
    [configButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    UIBarButtonItem *rightBarBtn1 = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    UIBarButtonItem *rightBarBtn2 = [[UIBarButtonItem alloc] initWithCustomView:configButton];
    self.navigationItem.rightBarButtonItems = @[rightBarBtn2,rightBarBtn1];
    
    [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf showMenu];
    }];
    
    [[configButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf plantGroupConfig];
    }];
    //    }
    
    __block NSInteger defaultIndex = 0;
    [self.titles enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([title isEqualToString:self.defaultTitle]) {
            defaultIndex = idx;
        }
    }];
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self.view addSubview:self.listContainerView];
    _listContainerView.scrollView.scrollEnabled = NO;
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.categoryView.titles = self.titles;
    self.categoryView.defaultSelectedIndex = defaultIndex;
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.cellWidth = 60;
    self.categoryView.titleSelectedColor = kCOLOR_HEX(@"#3DBB91");
    self.categoryView.titleColor = kCOLOR_HEX(@"#8B8D92");
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:14];
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = NO;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.cellSpacing = 30;
    //    self.categoryView.contentEdgeInsetLeft = 20;
    //    self.categoryView.contentEdgeInsetRight = 20;
    self.categoryView.titleLabelVerticalOffset = -10;
    [self.view addSubview:self.categoryView];
    self.categoryView.listContainer = self.listContainerView;
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.height.mas_equalTo(50);
    }];
    
    JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
    backgroundView.size = CGSizeMake(60, 3);
    backgroundView.indicatorColor = kCOLOR_HEX(@"#3DBB91");
    backgroundView.indicatorHeight = 3;
    backgroundView.indicatorWidth = 60;
    backgroundView.verticalMargin = -10;
    backgroundView.indicatorCornerRadius = 1.5;
    
    _categoryView.indicators = @[backgroundView];
    
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.equalTo(weakSelf.categoryView.mas_bottom);
    }];
    
}




-(void)showMenu
{
    kWeakSelf;
    NSMutableArray *menuItems = [[NSMutableArray alloc] initWithObjects:
                                 
                                 [IFMMenuItem itemWithImage:[UIImage imageNamed:@"kwt_add_plant2"]
                                                      title:@"添加电站".rh_localized
                                                     action:^(IFMMenuItem *item) {
        RHAddMePlantVC *addVC = [[RHAddMePlantVC alloc]init];
        [weakSelf.navigationController pushViewController:addVC animated:YES];
    }],[IFMMenuItem itemWithImage:[UIImage imageNamed:@"kwt_add_plant2"]
                            title:@"添加分组".rh_localized
                           action:^(IFMMenuItem *item) {
        KWTAddPlantGroupVC *addVC = [[KWTAddPlantGroupVC alloc]init];
        [weakSelf.navigationController pushViewController:addVC animated:YES];
    }],
                                 
                                 [IFMMenuItem itemWithImage:[UIImage imageNamed:@"kwt_add_plant2"]
                                                      title:@"添加设备".rh_localized
                                                     action:^(IFMMenuItem *item) {
        //添加设备
        RHAddDeviceController *addDeviceVC = [[RHAddDeviceController alloc]init];
        [weakSelf.navigationController pushViewController:addDeviceVC animated:YES];
    }],nil];
    if ([PrivateMange share].currentUser.operationType == OperationTypeIndustry) {
        IFMMenuItem *item = [IFMMenuItem itemWithImage:[UIImage imageNamed:@"kwt_add_plant2"]
                                                 title:@"添加系统".rh_localized
                                                action:^(IFMMenuItem *item) {
            RHAddAssetSystemVC *addSystemVC = [[RHAddAssetSystemVC alloc]init];
            [weakSelf.navigationController pushViewController:addSystemVC animated:YES];
        }];
        [menuItems insertObject:item atIndex:2];
    }
    IFMMenu *menu = [[IFMMenu alloc] initWithItems:menuItems];
    menu.menuCornerRadiu = 8;
    menu.showShadow = YES;
    menu.minMenuItemHeight = 45;
    menu.titleColor = [UIColor colorWithHexString:@"#474B53" alpha:1];
    menu.titleFont = [UIFont systemFontOfSize:15];
    menu.menuBackgroundStyle = IFMMenuBackgroundStyleLight;
    
    [menu showFromNavigationController:self.navigationController WithX:[UIScreen mainScreen].bounds.size.width-70];
}

#pragma mark ----- 批量策略配置
-(void)plantGroupConfig
{
    RHBatchPlantGroupConfigVC *configVC = [[RHBatchPlantGroupConfigVC alloc]init];
    [self.navigationController pushViewController:configVC animated:YES];
}

#pragma mark ----- 获取一键配置
-(void)getplantGroupGolobalConfig{
    [QMUITips showLoadingInView:kAppWindow];
    [RHGolobalSetModel startGetWithCompletionAPIKey:H_getPlantGroupForceConfig argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.vppConfigModel = resultModel.data;
            NSMutableArray *mtbArr = [NSMutableArray array];
            if (request.responseJSONObject[@"data"]) {
                RHGolobalSetModel *s40K = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][@"S40K LV1.0"]];
                RHGolobalSetModel *me233;
                if (request.responseJSONObject[@"data"][R_SM233120A0_US]) {
                    me233 = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][R_SM233120A0_US]];
                }
                if (request.responseJSONObject[@"data"][K_KS233125A0_US]) {
                    me233 = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][K_KS233125A0_US]];
                }
                if (request.responseJSONObject[@"data"][R_SM233120A0_EU]) {
                    me233 = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][R_SM233120A0_EU]];
                }
                if (request.responseJSONObject[@"data"][K_KS233125A0_EU]) {
                    me233 = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][K_KS233125A0_EU]];
                }
                if (s40K) {
                    [mtbArr addObject:s40K];
                }
                if (me233) {
                    [mtbArr addObject:me233];
                }
                
            }
            RHVppGroupSetView *setView = [[RHVppGroupSetView alloc]initWithConfig:mtbArr.copy];
            kWeakSelf;
            setView.configBlock = ^{
                //                UIViewController *vc = weakSelf.listContainerView.validListDict[@(1)];
                //                if ([vc isKindOfClass:[KWTPlantGroupListVC class]]) {
                //                    KWTPlantGroupListVC *groupVC = (KWTPlantGroupListVC*)weakSelf.listContainerView.validListDict[@(1)];
                //                    groupVC.configModel = weakSelf.vppConfigModel;
                //                }
            };
            [setView show];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}


#pragma mark - JXCategoryViewDelegate

// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    kWeakSelf;
    QMUIButton *addButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
    [addButton setImage:[UIImage imageNamed:@"kwt_add_plant"] forState:UIControlStateNormal];
    [addButton setBackgroundColor:UIColor.clearColor];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    QMUIButton *configButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
    [configButton setImage:[UIImage imageNamed:@"plant_chg_config2"] forState:UIControlStateNormal];
    [configButton setBackgroundColor:UIColor.clearColor];
    [configButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    UIBarButtonItem *rightBarBtn1 = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    UIBarButtonItem *rightBarBtn2 = [[UIBarButtonItem alloc] initWithCustomView:configButton];
    if ([[self.titles safeObjectAtIndex:index]isEqualToString:@"分组".rh_localized]) {
        self.navigationItem.rightBarButtonItems = @[rightBarBtn2,rightBarBtn1];
    }else{
        self.navigationItem.rightBarButtonItems = @[rightBarBtn1];
    }
    
    [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf showMenu];
    }];
    
    [[configButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf plantGroupConfig];
    }];
    
    
}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return  self.titles.count;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    //管理层 并且是工商储类型
    if ([[self.titles safeObjectAtIndex:index] isEqualToString:@"电站".rh_localized]) {
        RHMePlantListVC *vc = [[RHMePlantListVC alloc] init];
        kWeakSelf;
        //刷新
        vc.refreshBlock = ^() {
            //            weakSelf.searchView.searchTextField.text = nil;
            //        [weakSelf getPlantCount];
        };
        
        return vc;
    }else if([[self.titles safeObjectAtIndex:index] isEqualToString:@"分组".rh_localized]){
        return [[KWTPlantGroupListVC alloc]init];
    }else if([[self.titles safeObjectAtIndex:index] isEqualToString:@"系统".rh_localized]){
        return [[RHAssetSystemListVC alloc]init];
    }else if([[self.titles safeObjectAtIndex:index] isEqualToString:@"设备".rh_localized]){
        return [[RHDeviceListFilterVC alloc]init];
    }else if([[self.titles safeObjectAtIndex:index] isEqualToString:@"部件".rh_localized]){
        return [[RHEndpointVC alloc]init];
    }
    
    
    return [UIViewController new];
}






-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
